<template>
  <div style="padding:10px">
    <Row>
      <Col span="5">
      <div class="col">
        <Input v-model="whereMap.userName"
               placeholder="用户名"
               style="width: 90%
          
          " />
      </div>
      </Col>
      <Col span="5">
      <div class="col">
        <!-- <label>机构</label> -->
        <Select v-model="treeName"
                style="width:90%;"
                ref="treeSelect"
                placeholder="请选择机构类型">
          <Option v-for="item in list"
                  :value="item.code"
                  :key="item.code"
                  style="display: none;">{{ item.title }}</Option>
          <Tree :data="treeList"
                style="padding-left:20px"
                @on-select-change="changeTree"></Tree>
        </Select>
      </div>
      </Col>
      <Col span="5">
      <div class="col">
        <!-- <label>姓名</label> -->
        <Input v-model="whereMap.name"
               placeholder="姓名"
               style="width: 90%" />
      </div>
      </Col>
      <Col span="5">
      <div class="col">
        <!-- <label>姓名</label> -->
        <Select v-model="whereMap.userType"
                style="width:90%"
                placeholder="类型">
          <Option v-for="item in typeList"
                  :value="item.code"
                  :key="item.code">{{ item.name }}</Option>
        </Select>
      </div>
      </Col>
    </Row>
    <Row style="margin: 10px 0">
      <Col span="5">
      <div class="col">

        <!-- <label>类型</label> -->
        <Select v-model="whereMap.isOpen"
                style="width:90%"
                placeholder="状态">
          <Option v-for="item in statusList"
                  :value="item.code"
                  :key="item.code">{{ item.name }}</Option>
        </Select>

      </div>
      </Col>
      <Col span="2"
           offset="17">
      <div class="col">
        <Button type="primary"
                @click="getList"
                v-if="control.search">搜索</Button>

        <Button type="warning"
                style="margin-left: 10px"
                @click="reset"
                v-show="false">重置</Button>
      </div>
      </Col>

    </Row>
    <Table border
           :columns="columns"
           :data="data"
           style="margin: 20px 0">
      <template slot-scope="{ row }"
                slot="userType">
        <span v-if="row.type == 'ADMIN_USER'">管理员</span>
        <span v-if="row.type == 'NORMAL_USER'">用户</span>
      </template>
      <template slot-scope="{ row }"
                slot="isOpen">
        <span v-if="row.isOpen == 'USER_ENABLE'">启用</span>
        <span v-if="row.isOpen == 'USER_DISABLE'">禁用</span>
      </template>
      <template slot-scope="{ row }"
                slot="action">
        <a style="margin-right: 8px"
           @click="resetPassWord(row)"
           v-if='row.canBeEdit && control.reset'>重置密码</a>
        <a style="margin-right: 8px"
           @click="changeStatus(row)"
           v-show="row.isOpen == 'USER_ENABLE'"
           v-if='row.canBeEdit && control.close'>禁用</a>
        <a style="margin-right: 8px"
           @click="changeStatus(row)"
           v-show="row.isOpen == 'USER_DISABLE'"
           v-if='row.canBeEdit && control.open'>启用</a>
        <a @click="detail('detail', row)"
           v-if='control.detail'>详情</a>
      </template>
    </Table>
    <Page :total="this.page.total"
          :current="this.page.current"
          :page-size="this.page.pagesize"
          :page-size-opts="this.page.opts"
          show-elevator
          show-sizer
          show-total
          class="text-center pagination"
          @on-change="currentChange"
          @on-page-size-change="pageChange" />
    <Modal v-model="resetSign"
           title="提醒"
           @on-ok="resetOk"
           style="text-align: center">
      <p>用户密码将被重置为初始密码，确认重置吗？</p>
    </Modal>
  </div>
</template>

<script>
import CryptoJS from 'crypto-js/crypto-js'
export default {
  name: 'user-management',
  data() {
    return {
      name: '',
      cityList: [
        {
          value: 'New York',
          label: 'New York'
        },
        {
          value: 'London',
          label: 'London'
        },
        {
          value: 'Sydney',
          label: 'Sydney'
        },
        {
          value: 'Ottawa',
          label: 'Ottawa'
        },
        {
          value: 'Paris',
          label: 'Paris'
        },
        {
          value: 'Canberra',
          label: 'Canberra'
        }
      ],
      model1: '',
      columns: [
        {
          title: '序号',
          align: 'center',
          width: 70,
          render: (h, params) => {
            return h(
              'span',
              params.index + (this.page.current - 1) * this.page.pagesize + 1
            )
          }
        },
        {
          title: '用户名',
          key: 'userName',
          align: 'center'
        },
        {
          title: '姓名',
          key: 'name',
          align: 'center'
        },
        {
          title: '联系电话',
          key: 'tel',
          align: 'center'
        },
        {
          title: '机构',
          key: 'orgName',
          align: 'center'
        },
        {
          title: '类型',
          slot: 'userType',
          align: 'center'
        },
        {
          title: '状态',
          slot: 'isOpen',
          align: 'center'
        },
        {
          title: '操作',
          slot: 'action',
          width: 210,
          align: 'center'
        }
      ],
      data: [], //列表数据
      page: {
        current: 1,
        pagesize: 10,
        total: 0,
        opts: [10, 20, 50, 100]
      },
      whereMap: {
        //查询数据
        name: '',
        userName: '',
        objectId: '',
        orgType: '',
        userType: '',
        isOpen: ''
      },
      statusList: [], //状态列表
      typeList: [], //类型列表
      resetSign: false,
      userId: '',
      treeList: [],
      list: [],
      treeName: '',
      control: {}
    }
  },
  methods: {
    getTree() {
      this.$api.userManagement.getTree().then(res => {
        if (res.code == 200) {
          this.treeList = res.data

          this.list = []
          let code = res.data[0].code || 'code'
          let title = res.data[0].title
          this.list.push({ code, title })

          this.whereMap.orgType = res.data[0].type
          this.whereMap.objectId = res.data[0].objectId
          this.treeName = res.data[0].code || 'code'
          this.getList()
        } else {
          this.$Message.error(res.data.msg)
        }
      })
    },
    //递归树状结构
    getCheildItem(data) {
      let item = data
      const arr = []
      item.forEach(val => {
        let obj = {}
        obj.title = val.name
        obj.code = val.code
        obj.children = []
        if (val.children.length > 0) {
          obj.children = this.getCheildItem(val)
        }
        arr.push(obj)
      })
      return arr
    },
    changeTree(data) {
      if (data) {
        this.list = []
        // window.console.log(data)
        this.whereMap.orgType = data[0].type
        this.whereMap.objectId = data[0].objectId
        let code = data[0].code || 'code'
        let title = data[0].title
        this.list.push({ code, title })
        this.treeName = data[0].code || 'code'
        this.$refs.treeSelect.visible = false
        this.page.current = 1
      }
    },
    getList() {
      //查询列表
      var req = {
        currentPage: this.page.current || 1,
        pageSize: this.page.pagesize || 10,
        whereMap: this.whereMap
      }

      this.$api.userManagement.getList(req).then(res => {
        if (res.code === 200) {
          this.page.total = res.data.totalRecord
          this.data = res.data.resultObject
        }
      })
    },
    currentChange(current) {
      //翻页
      this.page.current = current
      this.getList()
    },
    pageChange(pagesize) {
      //改变页数
      this.page.pagesize = pagesize
      this.getList()
    },
    getStatus() {
      //获取状态列表
      this.$api.userManagement.getStatusList().then(res => {
        if (res.code === 200) {
          this.statusList = res.data
        }
      })
    },
    getTypes() {
      //获取类型列表
      this.$api.userManagement.getTypeList().then(res => {
        if (res.code === 200) {
          this.typeList = res.data
        }
      })
    },
    changeStatus(row) {
      //切换启用禁用
      let statu = row.isOpen == 'USER_ENABLE' ? 'USER_DISABLE' : 'USER_ENABLE'
      this.$api.userManagement
        .changeStatus({ userId: row.id, isOpen: statu })
        .then(res => {
          if (res.code == 200) {
            this.$Message.success(res.message)
            this.getList()
          } else {
            this.$Message.error('操作失败')
          }
        })
    },
    resetPassWord(row) {
      //重置密码
      this.resetSign = true
      this.userId = row.id
    },
    resetOk() {
      //modal弹框点击确认
      let password = this.encrypt('123456') //默认重置密码
      this.$api.userManagement
        .resetPassWord(this.userId, password)
        .then(res => {
          if (res.code === 200) {
            this.$Message.success('重置成功')
          }
        })
    },
    encrypt(word) {
      //加密
      var key = CryptoJS.enc.Utf8.parse('AZB_AES_PASSWORD')
      var srcs = CryptoJS.enc.Utf8.parse(word)
      var encrypted = CryptoJS.AES.encrypt(srcs, key, {
        mode: CryptoJS.mode.ECB,
        padding: CryptoJS.pad.Pkcs7
      })
      return encrypted.toString()
    },
    detail(type, row) {
      const route = {
        params: {
          type,
          id: row.id,
          name: '用户详情',
          row: row
        },
        name: 'user-management-detail'
      }
      this.$router.push(route)
    },
    reset() {
      this.whereMap.name = ''
      this.whereMap.userName = ''
      this.whereMap.userType = ''
      this.whereMap.isOpen = ''

      this.whereMap.orgType = this.treeList[0].type
      this.whereMap.objectId = this.treeList[0].objectId

      this.list = []
      let code = this.treeList[0].code || 'code'
      let title = this.treeList[0].title
      this.list.push({ code, title })
      this.treeName = code
      this.page = {
        current: 1,
        pagesize: 10,
        total: 0
      }
      this.getList()
    },
    //按钮权限
    buttonShow() {
      let buttonList = JSON.parse(localStorage.getItem('buttonList'))
      buttonList.map(val => {
        let key = Object.keys(val).toString()
        if (key === this.$route.name) {
          Object.values(val)[0].map(item => {
            if (item.code == 'P_0501_01') {
              this.control.open = true
            } else if (item.code == 'P_0501_02') {
              this.control.close = true
            } else if (item.code == 'P_0501_03') {
              this.control.reset = true
            } else if (item.code == 'P_0501_04') {
              this.control.detail = true
            } else if (item.code == 'P_0501_05') {
              this.control.search = true
            }
          })
        }
      })
    }
  },
  mounted() {
    this.getTree()
    this.getStatus()
    this.getTypes()
    this.buttonShow()
  },
  activated() {
    this.page.current = 1
    this.getList()
  }
}
</script>

<style lang="scss" scoped >
.col {
  padding: 5px;
  .col-item {
    display: inline-block;
    margin-right: 10px;
    label {
      display: block;
    }
  }
  label {
    display: block;
  }
}

.asterisk:before {
  content: '*';
}

.text-center {
  text-align: center;
}
</style>
